#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo"

trustee_operator_repo_dir="${kata_coco_top_dir}/trustee-operator"
trustee_operator_microservices_dir="${trustee_operator_repo_dir}/config/samples/microservices"
trustee_operator_test_dir="${trustee_operator_microservices_dir}/hygon"
reference_value_json_file="${trustee_operator_test_dir}/dbg-reference-values.json"

hygon_csv_type="csv"

usage () {
  set +x
  echo -e "\033[31m
Usage: $0 [-h] [-t <hygon-csv-type>]

       -h,--help Display this help message
       -t,--type Specify Hygon CSV type
                 Valid value are shown as following:
                     csv
                     csv2
                     csv3
                 Default is csv
\033[0m"
  set -x
}

params=$(getopt -o ht: --long help,type: -- "$@")
if [ $? -ne 0 ]; then
  echo "[Error] cannot parse parameters"
  exit 1
fi

eval set -- "$params"

while true; do
  case "$1" in
  -h|--help)
    usage
    exit 0
    ;;
  -t|--type)
    hygon_csv_type="$2"
    shift 2
    ;;
  --)
    shift
    break
    ;;
  *)
    usage
    exit 1
    ;;
  esac
done

# 计算启动度量值需要python的gmssl库，安装gmssl库
echo "[Install python3 gmssl]"
sudo yum install -y python3-pip
pip3 install gmssl

# 计算启动度量值
echo "[Calculate launch measurement]"
curl https://gitee.com/hanliyang-kata-coco/deployment/raw/master/tools/measurement/csv-calc-measurement.sh \
  -o /dev/shm/csv-calc-measurement.sh && \
chmod +x /dev/shm/csv-calc-measurement.sh && \
curl https://gitee.com/hanliyang-kata-coco/deployment/raw/master/tools/measurement/csv-measure.py \
  -o /dev/shm/csv-measure.py
pushd /dev/shm/
measure=$(./csv-calc-measurement.sh ${hygon_csv_type} | \
  grep "MEASUREMENT => " | sed "s/MEASUREMENT => //" | \
  sed 's/^[[:space:]]*//')
echo ${measure}
popd # /dev/shm

# Update reference value to kbs microservices's rvps
pushd ${trustee_operator_test_dir}
sed -i "/\"name\":\"measurement\"/s!\(^.*\)\(\]}$\)!\1,{\"alg\":\"sha384\",\"value\":\"${measure}\"}\2!" \
  ${reference_value_json_file}
./tool-operator-on-kbs-as-rvps.sh rvps "tee"
popd
